$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'storeGoodsProduct/storegoodsproduct/list',
        datatype: "json",
        colModel: [
			{ label: 'productId', name: 'productId', index: 'product_id', width: 50, key: true },
			{ label: '产品编号', name: 'productNo', index: 'product_no', width: 80 },
			{ label: '产品名称', name: 'productName', index: 'product_name', width: 80 },
			// { label: '价格', name: 'price', index: 'price', width: 80 },
			{ label: '重量', name: 'weight', index: 'weight', width: 80 },
			{ label: '单位', name: 'unit', index: 'unit', width: 80 },
			{ label: '规格属性', name: 'craft', index: 'craft', width: 80 },
			{ label: '商品类型', name: 'goodsType', index: 'goods_type', width: 80 },
			{ label: '门店分类', name: 'storeCategoryId', index: 'store_category_id', width: 80 },
			// { label: '商户id(作废)', name: 'sellerId', index: 'seller_id', width: 80 },
			{ label: '关联紫云网sku', name: 'origProductId', index: 'orig_product_id', width: 80 },
			// { label: '是否删除:1.是;0:否', name: 'disabled', index: 'disabled', width: 80 },
			// { label: '创建人', name: 'createName', index: 'create_name', width: 80 },
			// { label: '创建时间', name: 'createTime', index: 'create_time', width: 80 }
        ],
		viewrecords: true,
        height: 680,
        rowNum: 25,
		rowList : [25,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
    // 线获取添加模板基本信息
    $.get(baseURL + "goodsCategory/goodscategory/getCategoryTree", function(r){
        vm.categoryTree = r.addInfo.categoryTree;
    });
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "categoryId",
            pIdKey: "parentCategoryId",
            rootPId: -1
        },
        key: {
            name: "categoryName",
            url:"nourl"
        }
    }
};
var storeZtree;

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		storeGoodsProduct: {},
        storeGoodsProductList:[],
        spuTableData:null,
        skuTableData:null,
        outerVisible:false,
        innerVisible:false,
        outerVisible2:false,
        goodsCategoryDialogVisible:false,
        storeDialog:false,
        categoryId: null, //分类id
        categoryTree:[], //商品分类树
        spuQuery:{
            goodsId:null,
            name:null,
            catId:null
        },
        q:{
            productId:null,
            origProductId:null,
            productName:''
        },
		index:null,
	},
	methods: {
		//加载商品分类树
        getStoreGoodsCategory: function () {
            $.get(baseURL + "storeGoodsCategory/storegoodscategory/select", function (r) {
                storeZtree = $.fn.zTree.init($("#storeGoodsCategoryTree"), setting, r.storeGoodsCategoryList);
            })
        },
        //点击弹窗三级分类选择
        storeGoodsCategoryTree: function (parentIndex) {
            // vm.storeDialog = true;
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择门店父级分类",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#storeGoodsCategoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = storeZtree.getSelectedNodes();
					if(node.size == 0){
						alert("请选择分类")
						return;
					}
					if(node[0].parentCategoryId == 0 || node[0].parentCategoryId == -1){
                        alert("请不要选择父级分类")
                        return;
                    }
                    vm.storeGoodsProductList[parentIndex].storeCategoryId = node[0].categoryId;
                    vm.storeGoodsProductList[parentIndex].goodsType = node[0].goodsType;
                    layer.close(layer.index);
                }
            });
        },
		query: function () {
			vm.reload();
		},
        reset:function(){
          vm.q.productId = null;
          vm.q.origProductId = null;
          vm.q.productName = '';
          vm.reload();
        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.storeGoodsProductList = [];
            vm.getStoreGoodsCategory();
		},
		update: function (event) {
			var productId = getSelectedRow();
			if(productId == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            vm.storeGoodsProductList = [];
            vm.getStoreGoodsCategory();
            vm.getInfo(productId)
		},
		saveOrUpdate: function (event) {
            if(vm.validator()){
                return;
            }
			var url = vm.storeGoodsProduct.productId == null ? "storeGoodsProduct/storegoodsproduct/save" : "storeGoodsProduct/storegoodsproduct/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.storeGoodsProductList),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var productIds = getSelectedRows();
			if(productIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "storeGoodsProduct/storegoodsproduct/delete",
                    contentType: "application/json",
				    data: JSON.stringify(productIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(productId){
			$.get(baseURL + "storeGoodsProduct/storegoodsproduct/info/"+productId, function(r){
                vm.storeGoodsProduct = r.storeGoodsProduct;
                vm.storeGoodsProductList.push(vm.storeGoodsProduct);
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
                postData:{
                    productId:vm.q.productId,
                    origProductId:vm.q.origProductId,
                    productName:vm.q.productName.trim()
                }
            }).trigger("reloadGrid");
		},
        boundSku:function(index){
        	vm.index =  index;
			vm.outerVisible = true;

		},
        updateSku:function(index){
            vm.index =  index;
            vm.outerVisible = true;
        },
        choiceStoreCategoryId:function(index){
			vm.storeGoodsCategoryTree(index);
		},
        addStoreGoodsProduct:function(){
        	vm.storeGoodsProductList.push({storeCategoryId:null});
		},
        //树结构选中变化时
        categoryChange:function(value){
            //取到末级的分类id
            vm.catId = value[value.length-1];
            //根据分类请求后台判断分类属性
            var goodsCategory = {};
            $.get(baseURL+"goodsCategory/goodscategory/info/"+vm.catId,function(r){
                goodsCategory = r.goodsCategory;
                // if(goodsCategory.goodsType != 'standard'){
                //     this.$message.error('该功能只支持标品,请选择标品分类!');
                    // vm.$message({
                    //     showClose: true,
                    //     message: '该功能只支持标品,请选择标品分类!',
                    //     type: 'warning'
                    // });
                // }else{
                    //调用接下来的步骤
                    vm.goodsCategoryDialogVisible = false;
                    //加载spu数据
                    vm.loadSpuData();
                // }
            });
        },
        loadSpuData:function(){
            var query = {};
            if(!isBlank(vm.spuQuery.goodsId)){
                query.goods_id= vm.spuQuery.goodsId;
            }
            if(!isBlank(vm.spuQuery.name)){
                query.name= vm.spuQuery.name;
            }
            query.disabled = 0;
            query.category_id = vm.catId;
            query.self = 1;
            query.marketable = 'puton';
            // query.seller_id = 1;
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goods/goodsList",
                contentType: "application/json",
                data: JSON.stringify(query),
                success: function(r){
                    if(r.code == 0){
                        vm.spuTableData = r.spuTableData;
                    }else{
                        alert(r.msg);
                    }
                }
            });
            vm.skuTableData = null
        },
        //定义一个方法,获得数组里制定元素的集合
        getArrayProperties:function(array){
            var result = [];
            for(var i = 0;i<array.length;i++){
                result.push(array[i].origProductId);
            }
            return result;
        },
        choiceSpu:function(row){
            //做判断,如果是报价类商品,则直接添加
            if(row.goodsType == 'print' || row.goodsType == 'fast'){
                //vm.storeGoodsProductList[i].origProductId
                var origProductIds = vm.getArrayProperties(vm.storeGoodsProductList,"origProductId");
                var index = origProductIds.indexOf(row.goodsId)
                if(vm.title != '新增'){
                    //修改重新划分逻辑
                    var storeGoodsProduct = {};
                    storeGoodsProduct.storeCategoryId = null;
                    //选择完之后查询现在的分类有没有被门店分类所绑定,如果绑定了,则gtmddwh
                    $.get(baseURL + "storeGoodsCategory/storegoodscategory/getStoreCategoryByZYCatId/"+vm.catId, function(r){
                        if(r.storeGoodsCategory != null){
                            //若已经绑定分类,则直接绑定门店分类
                            storeGoodsProduct.storeCategoryId = r.storeGoodsCategory.categoryId;
                        }
                    });
                    storeGoodsProduct.goodsType = row.goodsType;
                    storeGoodsProduct.goodsFlag = 'spu';
                    storeGoodsProduct.origProductId = row.goodsId;
                    storeGoodsProduct.productName = row.name;
                    if(vm.storeGoodsProductList.length == 1){
                        vm.storeGoodsProductList[0].storeCategoryId = null;
                        vm.storeGoodsProductList[0].goodsType = row.goodsType;
                        vm.storeGoodsProductList[0].goodsFlag = 'spu';
                        vm.storeGoodsProductList[0].origProductId = row.goodsId;
                        vm.storeGoodsProductList[0].productName = row.name;
                        vm.storeGoodsProductList[0].disabled = 0;
                        vm.storeGoodsProductList[0].weight = null;
                        vm.storeGoodsProductList[0].craft = null;
                        vm.storeGoodsProductList[0].unit = null;
                        // vm.storeGoodsProductList.push(storeGoodsProduct);
                    }else{
                        alert("修改门店报价商品出错,请联系管理员")
                    }
                }else{
                    //新增照旧
                    if(index != -1 ){
                        //做删除操作
                        this.$confirm('此报价商品已存在, 是否移除?', '提示', {
                            confirmButtonText: '移除',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            vm.storeGoodsProductList.splice(index,1);
                            this.$message({
                                type: 'success',
                                message: '移除成功!'
                            });
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消移除'
                            });
                        });
                    }else{
                        this.$confirm('报价商品无sku,双击将直接添加商品, 是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            var storeGoodsProduct = {};
                            storeGoodsProduct.storeCategoryId = null;
                            //选择完之后查询现在的分类有没有被门店分类所绑定,如果绑定了,则gtmddwh
                            $.get(baseURL + "storeGoodsCategory/storegoodscategory/getStoreCategoryByZYCatId/"+vm.catId, function(r){
                                if(r.storeGoodsCategory != null){
                                    //若已经绑定分类,则直接绑定门店分类
                                    storeGoodsProduct.storeCategoryId = r.storeGoodsCategory.categoryId;
                                }
                            });
                            storeGoodsProduct.goodsType = row.goodsType;
                            storeGoodsProduct.goodsFlag = 'spu';
                            storeGoodsProduct.origProductId = row.goodsId;
                            storeGoodsProduct.productName = row.name;
                            vm.storeGoodsProductList.push(storeGoodsProduct);
                            this.$message({
                                type: 'success',
                                message: '添加成功!'
                            });
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消添加'
                            });
                        });
                    }
                }
            }else{
                var goodsId = row.goodsId
                if(isBlank(goodsId)){
                    vm.$message({
                        showClose: true,
                        message: '异常信息:spu不存在,请联系管理员!',
                        type: 'warning'
                    });
                    return;
                }
                var skuQuery = {}
                skuQuery.disabled = 0;
                skuQuery.goods_id = goodsId;
                $.ajax({
                    type: "POST",
                    url: baseURL + "goods/goodsproduct/selectProductByGoodsId",
                    contentType: "application/json",
                    data: JSON.stringify(skuQuery),
                    success: function(r){
                        if(r.code == 0){
                            vm.skuTableData = r.skuTableData;
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }
        },
        choiceSku:function(row){
            var storeGoodsProduct = {};
            storeGoodsProduct.storeCategoryId = null;
            //选择完之后查询现在的分类有没有被门店分类所绑定,如果绑定了,则gtmddwh
            $.get(baseURL + "storeGoodsCategory/storegoodscategory/getStoreCategoryByZYCatId/"+vm.catId, function(r){
                if(r.storeGoodsCategory != null){
                    //若已经绑定分类,则直接绑定门店分类
                    storeGoodsProduct.storeCategoryId = r.storeGoodsCategory.categoryId;
                }
                // else{
                    //若无分类绑定,则随机选择绑定门店分类
                // }
            });
            //根据skuId获得商品类型
            $.get(baseURL + "goods/goodsproduct/getGoodsType/"+row.productId, function(r){
                storeGoodsProduct.goodsType = r.goodsType;
                storeGoodsProduct.pricingManner = r.type;
            });

            if(vm.title != '新增'){
                //修改只需要直接改变值
                if(vm.storeGoodsProductList.length ==1){
                    vm.storeGoodsProductList[0].productName = row.goodsName;
                    vm.storeGoodsProductList[0].weight = row.weight;
                    vm.storeGoodsProductList[0].craft = row.optionNames;
                    vm.storeGoodsProductList[0].unit = row.unit;
                    vm.storeGoodsProductList[0].origProductId = row.productId;
                    vm.storeGoodsProductList[0].storeCategoryId = null;
                    vm.storeGoodsProductList[0].goodsType = null;
                    vm.storeGoodsProductList[0].disabled = 0;
                    vm.storeGoodsProductList[0].goodsFlag = 'sku';
                }else{
                    alert("修改门店标品类商品出错,请联系管理员")
                }
            }else{
                //获得skuId和规格属性中文
                //productName price weight unit craft origProductId
                storeGoodsProduct.productName = row.goodsName;
                // storeGoodsProduct.price = row.totalPrice;
                storeGoodsProduct.weight = row.weight;
                storeGoodsProduct.craft = row.optionNames;
                storeGoodsProduct.unit = row.unit;
                storeGoodsProduct.origProductId = row.productId;
                storeGoodsProduct.storeCategoryId = null;
                storeGoodsProduct.goodsType = null;
                storeGoodsProduct.disabled = 0;
                storeGoodsProduct.goodsFlag = 'sku';
                if(row.addOrDel == false){
                    row.addOrDel = true;
                    vm.storeGoodsProductList.push(storeGoodsProduct);
                }else{
                    row.addOrDel = false;
                    //将
                    for(var i = 0 ;i<vm.storeGoodsProductList.length;i++){
                        if(vm.storeGoodsProductList[i].origProductId == row.productId) {
                            vm.storeGoodsProductList.splice(i,1);
                            break;
                        }
                    }
                }
            }
		},
		//删除行记录
        delRow:function(index){
        	vm.storeGoodsProductList.splice(index,1);
		},
        addAll:function(){
            vm.skuTableData
            alert("添加全部")
            $.get(baseURL + "storeGoodsCategory/storegoodscategory/getStoreCategoryByZYCatId/"+vm.catId, function(r){
                for(var i = 0;i<vm.skuTableData.length;i++){
                    var row = vm.skuTableData[i];
                    var storeGoodsProduct = {};
                    storeGoodsProduct.storeCategoryId = null;
                    if(r.storeGoodsCategory != null){
                        //若已经绑定分类,则直接绑定门店分类
                        storeGoodsProduct.storeCategoryId = r.storeGoodsCategory.categoryId;
                    }
                    storeGoodsProduct.goodsType = r.categoryEntity.goodsType;
                    storeGoodsProduct.pricingManner =  r.categoryEntity.pricingManner;
                    storeGoodsProduct.productName = row.goodsName;
                    // storeGoodsProduct.price = row.totalPrice;
                    storeGoodsProduct.weight = row.weight;
                    storeGoodsProduct.craft = row.optionNames;
                    storeGoodsProduct.unit = row.unit;
                    storeGoodsProduct.origProductId = row.productId;
                    storeGoodsProduct.disabled = 0;
                    vm.skuTableData[i].addOrDel = true;
                    vm.storeGoodsProductList.push(storeGoodsProduct);
                }
            });

        },
        validator:function(){
            ;
            for(var i = 0;i < vm.storeGoodsProductList.length;i++){
                if(isBlank(vm.storeGoodsProductList[i].storeCategoryId)){
                    alert("必须绑定门店id")
                    return true;
                }
                if(isBlank(vm.storeGoodsProductList[i].productName)){
                    alert("商品名不能为空")
                    return true;
                }
            }
            return false;
        }
	}
});